const fs = require('fs').promises;
const path = require('path');

const categoriesDir = path.join(__dirname, '../../database/categories');

// 获取所有分类列表
async function getAllCategories() {
  try {
    const files = await fs.readdir(categoriesDir);
    const categoryFiles = files.filter(file => file.endsWith('.json'));
    
    const categories = await Promise.all(
      categoryFiles.map(async (file) => {
        const data = await fs.readFile(path.join(categoriesDir, file), 'utf8');
        return JSON.parse(data);
      })
    );
    
    return categories;
  } catch (error) {
    if (error.code === 'ENOENT') {
      // 目录不存在，创建目录并返回空数组
      await fs.mkdir(categoriesDir, { recursive: true });
      return [];
    }
    throw error;
  }
}

// 根据ID获取分类
async function getCategoryById(id) {
  try {
    const filePath = path.join(categoriesDir, `${id}.json`);
    const data = await fs.readFile(filePath, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    if (error.code === 'ENOENT') {
      return null;
    }
    throw error;
  }
}

// 创建新分类
async function createCategory(categoryData) {
  try {
    const filePath = path.join(categoriesDir, `${categoryData.id}.json`);
    await fs.writeFile(filePath, JSON.stringify(categoryData, null, 2), 'utf8');
    return categoryData;
  } catch (error) {
    throw error;
  }
}

// 更新分类
async function updateCategory(id, categoryData) {
  try {
    const filePath = path.join(categoriesDir, `${id}.json`);
    // 检查文件是否存在
    await fs.access(filePath);
    
    await fs.writeFile(filePath, JSON.stringify(categoryData, null, 2), 'utf8');
    return categoryData;
  } catch (error) {
    if (error.code === 'ENOENT') {
      return null;
    }
    throw error;
  }
}

// 删除分类
async function deleteCategory(id) {
  try {
    const filePath = path.join(categoriesDir, `${id}.json`);
    await fs.unlink(filePath);
    return true;
  } catch (error) {
    if (error.code === 'ENOENT') {
      return false;
    }
    throw error;
  }
}

module.exports = {
  getAllCategories,
  getCategoryById,
  createCategory,
  updateCategory,
  deleteCategory
}; 